package com.xyh.flowershop.strategy;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONObject;
import com.xyh.flowershop.constant.CacheConstant;
import com.xyh.flowershop.constant.CommonConstant;
import com.xyh.flowershop.domain.User;
import com.xyh.flowershop.domain.UserExtend;
import com.xyh.flowershop.enums.LoginEnum;
import com.xyh.flowershop.service.UserExtendService;
import com.xyh.flowershop.service.UserService;
import com.xyh.flowershop.service.WechatService;
import com.xyh.flowershop.utils.CommonUtils;
import com.xyh.flowershop.vo.req.user.LoginUser;
import com.xyh.flowershop.vo.resp.user.WxUserRespVo;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author 小约翰可汗
 * @className WxOpenIdLogin
 * @createTime 2024/7/1413:28
 */
@Component
public class WxOpenIdLogin extends AbstractLogin {

    private final WechatService wechatService;

    private final UserExtendService userExtendService;

    private final UserService userService;

    public WxOpenIdLogin(WechatService wechatService, UserExtendService userExtendService, UserService userService) {
        this.wechatService = wechatService;
        this.userExtendService = userExtendService;
        this.userService = userService;
    }


    @Override
    public String login(LoginUser loginUser) {
        String userId = "";
        JSONObject jsonObject = wechatService.wxLogin(loginUser.getLoginToken());
        String openId = jsonObject.getStr("openid");
        WxUserRespVo wxUser = userService.findUser(openId,"");
        if(Objects.isNull(wxUser)){
            User user = fromUser();
            userService.save(user);
            userId = user.getId();
            UserExtend extend = fromUserExtend(jsonObject.getStr("openid"), jsonObject.getStr("session_key"),userId );
            userExtendService.save(extend);
        }else{
            String sessionKey = wxUser.getSessionKey();
            userId = wxUser.getId();
            if(!sessionKey.equals(jsonObject.getStr("session_key"))){
                userExtendService.updateSessionKey(wxUser.getOpenId(), jsonObject.getStr("session_key"));
            }
        }
        String token = creatToken(userId);
        redisCache.setCacheObject(CacheConstant.LOGIN_PREFIX + token, userId);
        return token;
    }

    @Override
    protected Integer getType() {
        return LoginEnum.WX_LOGIN.getCode();
    }

    private User fromUser( ){
        User user = new User();
        String userName = CommonUtils.randomUser();
        Boolean exist = userService.checkUserIsExist(userName);
        while (exist){
            userName = CommonUtils.randomUser();
            exist = userService.checkUserIsExist(userName);
        }
        user.setUserName(userName);
        user.setAccount(CommonUtils.randomUser());
        user.setCreateTime(new Date());
        // 默认密码
        user.setPassword(MD5.create().digestHex(CommonConstant.DEFAULT_PASSWORD));
        return user;
    }

    private UserExtend fromUserExtend(String openId, String sessionKey, String userId){
        UserExtend extend = new UserExtend();
        extend.setUserId(userId);
        extend.setSessionKey(sessionKey);
        extend.setOpenId(openId);
        return extend;
    }
}
